<template>
  <div class="customer-manage-container">
    <el-card class="customer-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="用户名/昵称/手机号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              class="status-search"
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="全部" value="all" />
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 客户列表 -->
      <el-table v-loading="loading" :data="customerList" style="width: 100%" border>
        <el-table-column label="客户信息" min-width="100">
          <template #default="{ row }">
            <div class="customer-info">
              <el-avatar :size="40" :src="row.avatar">
                {{ row.nickname?.charAt(0) || row.username.charAt(0) }}
              </el-avatar>
              <div class="info-detail">
                <div class="username">{{ row.username }}</div>
                <div class="nickname" v-if="row.nickname">{{ row.nickname }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="手机号" width="120">
          <template #default="{ row }">
            {{ row.phone || '空' }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="180">
          <template #default="{ row }">
            {{ row.email || '空' }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- <el-table-column prop="totalOrders" label="订单数" width="80" align="center" />
        <el-table-column prop="totalAmount" label="消费金额" width="120" align="right">
          <template #default="{ row }"> ¥{{ row.totalAmount.toFixed(2) }} </template>
        </el-table-column> -->

        <el-table-column prop="created_at" label="注册时间" width="180" />

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
            <el-button
              :type="row.is_active ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" title="编辑客户信息" width="500px">
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <el-form-item label="头像" class="avatar-item">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              :before-upload="beforeUpload"
              :limit="1"
            >
              <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <!-- <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled />
          </el-form-item> -->
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Customer, CustomerQuery, CustomerUpdateDto } from '@/types/customer'
import { getCustomers, updateCustomerStatus, updateCustomerInfo } from '@/api/user'
import type { FileItem, UploadFile } from '@/types/upload'
import { uploadAvatarWithUserId } from '@/api/upload'
import { v4 as uuidv4 } from 'uuid'
import { beforeUpload } from '@/utils/upload'

// 搜索表单
const searchForm = reactive<CustomerQuery>({
  keyword: '',
  status: 'all',
  page: 1,
  pageSize: 10,
})

const singleFile = reactive<FileItem>({
  uid: '',
  name: '',
  status: 'ready',
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 客户列表数据
const customerList = ref<Customer[]>([])

// 编辑相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const editForm = reactive<CustomerUpdateDto & { username: string }>({
  id: 0,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
})

// 表单验证规则
const rules = reactive<FormRules>({
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getCustomers({
      keyword: searchForm.keyword,
      status: searchForm.status,
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    customerList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 切换状态
const handleToggleStatus = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(`确定要${row.is_active ? '禁用' : '启用'}该用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await updateCustomerStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 保存编辑
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        const { id, username, ...updateData } = editForm
        await updateCustomerInfo(id, updateData)
        ElMessage.success('保存成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = 'all'
  currentPage.value = 1
  fetchData()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

// 编辑客户
const handleEdit = (row: Customer) => {
  Object.assign(editForm, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    email: row.email,
    phone: row.phone,
    avatar: row.avatar,
  })
  dialogVisible.value = true
}

// 处理头像上传
const handleAvatarChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    Object.assign(singleFile, {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    })

    try {
      if (!singleFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      singleFile.status = 'uploading'
      singleFile.percentage = 0

      const response = await uploadAvatarWithUserId(singleFile.raw, editForm.id, (percentage) => {
        singleFile.percentage = percentage
      })

      singleFile.status = 'success'
      editForm.avatar = response.data.data.url
      ElMessage.success('上传成功')
    } catch (error) {
      singleFile.status = 'error'
      ElMessage.error('上传失败')
    }
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.customer-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.customer-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.customer-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-detail {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
}

.nickname {
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.status-search {
  width: 100px;
}
</style>
